package com.szt.ynb.server.router.controller.api;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.szt.ynb.server.router.entity.Server;
import com.szt.ynb.server.router.service.ServerService;
import com.szt.ynb.server.router.service.SignService;
import com.szt.ynb.server.router.vo.base.RepBaseVO;

@RestController
@RequestMapping("api/server")
public class ApiServerController {
	
	@Autowired
	private ServerService serverService;
	
	@Autowired
	private SignService signService;
	
	/****
	 * 获取服务器列表
	 * 
	 * @param serverName
	 * @param version
	 * @return
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@RequestMapping("list")
	public RepBaseVO getServerList(String serverName, String version) {
		RepBaseVO repVO = new RepBaseVO<>();
		List<Server> servers = serverService.findAllValidByServerNameAndVersion(serverName, version);
		return repVO.setCommonSuccess().setData(servers);
	}
	
	/***
	 * 服务上线
	 * 
	 * @param serverName
	 * @param url
	 * @param version
	 * @return
	 */
	@RequestMapping("up")
	public RepBaseVO serverUp(String serverName, String url, String version, @RequestParam Map<String, String> params) {
		RepBaseVO repVO = new RepBaseVO<>();
		if (!signService.checkSign(params)) {
			return repVO.setCommonFail().setMes("签名错误");
		}
		Server server = serverService.findByServerNameAndVersionAndUrl(serverName, version, url);
		if (server == null) {
			serverService.addServer(url, serverName, version);
		} else {
			serverService.online(server.getId());
		}
		return repVO.setCommonSuccess();
	}
	
	/***
	 * 服务下线
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping("down")
	public RepBaseVO serverDown(Long id, @RequestParam Map<String, String> params) {
		RepBaseVO repVO = new RepBaseVO<>();
		if (!signService.checkSign(params)) {
			return repVO.setCommonFail().setMes("签名错误");
		}
		serverService.offline(id);
		return repVO.setCommonSuccess();
	}
	
}
